﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;

namespace TushuGuan_GUI
{
    public class BookList
    {
        const int banben = 1;
        public List<Book> Books { get; set; } = new List<Book>();

        public BookList()
        {
            Load();
        }
        public void Addbook(string iSBN)
        {
            Book book = new Book
            {
                ISBN = iSBN,
                StudentID = ""
            };
            Books.Add(book);
            Save();
        }
        public void RemoveBook(string iSBN)
        {
            for (int i = 0; i < Books.Count; i++)
            {
                if (Books[i].ISBN == iSBN)
                {
                    Books.RemoveAt(i);
                }
            }
            Save();
        }
        public List<Book> SearchBooks(string isbn)
        {
            List<Book> result = new List<Book>();
            foreach (Book book in Books)
            {
               
                if (book.ISBN.IndexOf(isbn) > -1)
                {
                    result.Add(book);
                }
            }
            Save();

            return result;
        }
        public bool RemoveBook(List<int> booksRemove)
        {
            bool if_success = true;
            List<string> booksISBN = new List<string>();
            for (int i = 0; i < booksRemove.Count; i++)
            {
                try
                {
                    booksISBN.Add(Books[booksRemove[i] - 1].ISBN);
                }
                catch
                {
                    if_success = false;
                }
            }
            for (int i = 0; i < booksISBN.Count; i++)
            {
                try
                {
                    RemoveBook(booksISBN[i]);
                }
                catch
                {
                    if_success = false;
                }
            }
            return if_success;
        }

        public void LendBook(string isbn, string studentId)
        {
            Book book_ = null;
            for (int i = 0; i < Books.Count; i++)
            {
                if (Books[i].ISBN == isbn)
                {
                    book_ = Books[i];
                }
            }
            if (book_ == null)
            {
                throw new Exception("找不到此书：" + isbn);
            }
            book_.Lend(studentId);
            Save();
        }
        public void ReturnBook(string isbn, string studentId)
        {
            Book book_ = null;
            for (int i = 0; i < Books.Count; i++)
            {
                if (Books[i].ISBN == isbn)
                {
                    book_ = Books[i];
                }
            }
            if (book_ == null)
            {
                throw new Exception("找不到此书：" + isbn);
            }
            book_.Return();

            Save();
        }

        public void Save()
        {
            //序列化
            JObject data = new JObject(new JProperty("banben", banben));
            data.Add(new JProperty("Count", Books.Count));
            for (int i=0;i<Books.Count;i++)
            {
                data.Add(new JProperty(i.ToString(), Books[i].Save()));
            }
            //保存
            //新建文件
            FileStream xiaFile = new FileStream("books.json", FileMode.Create);
            //写入
            byte[] buf = Encoding.UTF8.GetBytes(data.ToString());
            xiaFile.Write(buf, 0, buf.Length);
            xiaFile.Flush();
            xiaFile.Close();
        }
        public void Load()
        {
            try
            {
                //打开文件
                FileInfo fi = new FileInfo("books.json");
                long len = fi.Length;

                FileStream fs = new FileStream("books.json", FileMode.Open);
                byte[] buffer = new byte[len];
                fs.Read(buffer, 0, (int)len);//读取文件
                fs.Close();//关闭
                string str = Encoding.UTF8.GetString(buffer);//转码
                var json = (JObject)JsonConvert.DeserializeObject(str);
                switch (int.Parse(json["banben"].ToString()))
                {
                    case 1:
                        Load_1(str);
                        break;
                    default:
                        return;
                }
                if(int.Parse(json["banben"].ToString())!=banben)
                {
                    Save();
                }
            }
            catch
            {
                Save();
            }
        }

        public void Load_1(string data)
        {
            var json = (JObject)JsonConvert.DeserializeObject(data);
            var Count = json["Count"];
            int count_ = int.Parse(Count.ToString());

            Books.Clear();
            for (int i = 0; i < count_; i++)
            {
                var linshi = json[i.ToString()];
                Book book = new Book();
                book.Load(linshi.ToString());

                Books.Add(book);
            }
        }
    }
}
